<template>
	<view class="page">
		<view class="score-list">
			<view class="score u-border-bottom" v-for="(item, index) in getScoreData(scoreList)" :key="item._id">
				<text>姓名: {{ item.username }}</text>
				<text>得分: {{ item.score }}</text>
			</view>

			<uni-load-more :status="loadStatus" />
		</view>
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad, onShow, onReady, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'

const loadStatus = ref('more')
const scoreList = ref([])

const pagination = {
	pageNum: 1,
	pageSize: 10
}

onLoad(() => {
	getScoreList()
})

onPullDownRefresh(() => {
	pagination.pageNum = 1
	getScoreList().then(() => {
		uni.stopPullDownRefresh()
	})
})

onReachBottom(() => {
	if (['loading', 'noMore'].includes(loadStatus.value)) return
	loadStatus.value = 'loading'
	pagination.pageNum += 1
	getScoreList()
})

const getScoreData = data => {
	const obj = {}
	const arr = data
		.sort((a, b) => Number(b.score.slice(0, -1)) - Number(a.score.slice(0, -1)))
		.reduce((acc, c) => {
			obj[c.username] ? '' : (obj[c.username] = true && acc.push(c))
			return acc
		}, [])
	return arr
}

const getScoreList = async () => {
	const compare = uniCloud.importObject('compare')
	try {
		const res = await compare.getAllScore({
			pageNum: pagination.pageNum,
			pageSize: pagination.pageSize
		})
		console.log(res)
		if (getScoreData(res.data).length < pagination.pageSize || res.data.length === 0) {
			loadStatus.value = 'noMore'
		}
		scoreList.value = pagination.pageNum === 1 ? res.data : [...scoreList.value, ...res.data]
	} catch (e) {
		console.log(e.errMsg)
	}
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
